//upyun不允许最后一个chunk的内容少于
//upyun  file_size (单位 bit) 
var saveToken;
var upyunchunk;//upyun chunk 数量
//var globalSize=33554432;//单位bit 4M  
//var globalSize=8388608;//单位bit 1M  
var globalSize=4194304;//单位bit 512KB
var globalIndex=0;//默认单线程时 上传到哪个文件的下标
var blockshash=[];//存每个分块的md5 
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var chunkInfo={
                'file_blocks': 1,
                'file_size': 0,
                'file_hash': "",
        }
var config = {
    bucket:'chuhaiwang', //never
    expiration: parseInt((new Date().getTime() + 3600000) / 1000),
    // 尽量不要使用直接传表单 API 的方式，以防泄露造成安全隐患
    //form_api_secret: '1+JY2ZqD5UVfw6hQ8EesYQO50Wo=',
    form_api_secret: 'OC6paP1wvtL/dFqnLZ06x3ACl30=',   //nGvzYOS5MyH+QsDhUugFX89Up+o=
    api: 'http://m0.api.upyun.com/',
    chunkSize: globalSize
};
var Base64 = {
      // private property
        _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        // public method for encoding
        encode : function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = Base64._utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
            }
            return output;
        },
        // public method for decoding
        decode : function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = this._keyStr.indexOf(input.charAt(i++));
                enc2 = this._keyStr.indexOf(input.charAt(i++));
                enc3 = this._keyStr.indexOf(input.charAt(i++));
                enc4 = this._keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = Base64._utf8_decode(output);
            return output;
        },
        // private method for UTF-8 encoding
        _utf8_encode : function (string) {
            string = string.replace(/\r\n/g,"\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                }
                else if((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        },
        // private method for UTF-8 decoding
        _utf8_decode : function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while ( i < utftext.length ) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                }
                else if((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i+1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                }
                else {
                    c2 = utftext.charCodeAt(i+1);
                    c3 = utftext.charCodeAt(i+2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    };
function formatParams(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    return arr.join("&");
}
function sortPropertiesByKey(obj) {
        var keys = [];
        var sorted_obj = {};
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
        keys.sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            sorted_obj[k] = obj[k];
        }
        return sorted_obj;
    }

//生成signature 的算法 
function calcSign(data, secret) {
            if (typeof data !== 'object') {
                return;
            }
            var sortedData = sortPropertiesByKey(data);
            var md5Str = '';
            for (var key in sortedData) {
                if (key !== 'signature') {
                    md5Str = md5Str + key + sortedData[key];
                }
            }
            //console.log("md5str  ",md5Str,"secret  ",secret);
            var sign = SparkMD5.hash(md5Str + secret);
            return sign;
        }


jQuery(function() {

    var $ = jQuery,    // just in case. Make sure it's not an other libaray.

        $wrap = $('#uploader'),

        // 图片容器
        $queue = $('<ul class="filelist"></ul>')
            .appendTo( $wrap.find('.queueList') ),

        // 状态栏，包括进度和控制按钮
        $statusBar = $wrap.find('.statusBar'),

        // 文件总体选择信息。
        $info = $statusBar.find('.info'),

        // 上传按钮
        $upload = $wrap.find('.uploadBtn'),

        // 没选择文件之前的内容。
        $placeHolder = $wrap.find('.placeholder'),

        // 总体进度条
        $progress = $statusBar.find('.progress').hide(),

        // 添加的文件数量
        fileCount = 0,

        // 添加的文件总大小
        fileSize = 0,

        // 优化retina, 在retina下这个值是2
        ratio = window.devicePixelRatio || 1,

        // 缩略图大小
        // thumbnailWidth = 110 * ratio,
        // thumbnailHeight = 110 * ratio,

        // 可能有pedding, ready, uploading, confirm, done.
        state = 'pedding',

        // 所有文件的进度信息，key为file id
        percentages = {},

        supportTransition = (function(){
            var s = document.createElement('p').style,
                r = 'transition' in s ||
                      'WebkitTransition' in s ||
                      'MozTransition' in s ||
                      'msTransition' in s ||
                      'OTransition' in s;
            s = null;
            return r;
        })(),

        // WebUploader实例
        uploader;


    //Token
    function getToken(file){
        //file.size 是webuploader传来用在upyun  单位是B要乘8
        var filesize=file.size*8;
        
        console.log("文件大小",file.size,"B");

        upyunchunk=Math.ceil(filesize/config.chunkSize);
        if(upyunchunk==0)
            upyunchunk=1;

        console.log("upyun->块数",upyunchunk,"单块大小",(globalSize/8),"B");
        chunkInfo.file_blocks=upyunchunk;

        //这里的path必须为字符串
        //notify_url为回调后台的url
        var options = {
                'path': new Date().getTime()+"",
                'expiration': config.expiration,
                'file_blocks': chunkInfo.file_blocks,
                'file_size': chunkInfo.file_size,
                'file_hash': chunkInfo.file_hash,
                //'notify_url': 'http://upyun.com' 
            };

        var signature = calcSign(options, config.form_api_secret);

        var policy = Base64.encode(JSON.stringify(options));
        var paramsData = {
            policy: policy,
            signature: signature
        };

        //初始化upyun上传
        var urlencParams = formatParams(paramsData);
        var request = new XMLHttpRequest();
        request.open('POST', config.api + config.bucket + '/');
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.onload = function(e) {
            if (request.status == 200) {
                // if (JSON.parse(request.response).status.indexOf(0) < 0) {
                //     console.log('file already exists');
                // }
                saveToken=JSON.parse(request.response);
                //console.log(chunkInfo, request.response);
                console.log("savetoken",saveToken);
            } else {
                request.send(urlencParams);
            }
        };
        request.send(urlencParams);

        var baiduChunkSize=config.chunkSize/8;//B

        //直接开始计算分块的md5
        //blockshash=new Array(upyunchunk);
        for(var i=0;i<upyunchunk;i++){
            var fileReader = new FileReader();
            fileReader.index=i;
            var start = i*baiduChunkSize;
            var end=(i+1)*baiduChunkSize;
            if(end>file.size)
                end=file.size;
            //console.log("chunk i",start,"-->",end);
            var blobPacket = blobSlice.call(file.getSource().source,start,end);
            fileReader.onload=function(e){
                blockshash[this.index]=SparkMD5.ArrayBuffer.hash(e.target.result);
                console.log("block ",this.index," md5=>",blockshash[this.index]);
                //hash 数组长度是否等于block 数
                // console.log(blockshash.length,upyunchunk)
                // console.log(blockshash[upyunchunk-1]);
                var percent =  (this.index+1) / upyunchunk ;
                

                if(this.index==upyunchunk-1){
                       $(".loading").remove();
                       $(".uploadBtn").show();
                }
                // if(this.index==upyunchunk-1){
                //     //全部初始化完毕
                //     //$(".loading").remove();
                //     //$(".uploadBtn").show();
                //     console.log('chunks loaded');
                // }else{
                //     console.log($(".loading"),Math.round( percent * 100 ) );

                //     $(".loading").text("正在初始化上传 "+ Math.round( percent * 100 ) + '%' );
                // }
            }
            fileReader.readAsArrayBuffer(blobPacket);
        }
    }




    if ( !WebUploader.Uploader.support() ) {
        alert( 'Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
        throw new Error( 'WebUploader does not support the browser you are using.' );
    }

    // 实例化
    uploader = WebUploader.create({
        //runtimeOrder:'flash',
        pick: {
            id: '#filePicker',
            label: '选择文件'
        },
        dnd: '#uploader .queueList',
        paste: document.body,

        accept: {
            title: 'Images',
            extensions: '*',
            mimeTypes: ''
        },

        // swf文件路径
        swf: BASE_URL + '/js/Uploader.swf',

        disableGlobalDnd: true,

        chunked: true,
        //server: 'http://localhost:8999/users/upload',
        server:config.api + config.bucket + '/',
        retry:3,
        fileNumLimit: 1,//one file 
        fileSizeLimit: 300 * 1024 * 1024,    // 200 M
        fileSingleSizeLimit: 300 * 1024 * 1024,    // 1G single file limit 
        chunkSize:globalSize/8,    //4.5M 默认  单位B
        threads:1,  //允许同时最大上传进程数。
        compress:null
    });
    //console.log(uploader)
    // 添加“添加文件”的按钮，
    // uploader.addButton({
    //     id: '#filePicker2',
    //     label: '继续添加'
    // });

    //每个分块上传前的调整
    uploader.on( 'uploadBeforeSend', function( block, data ) {
        // block为分块数据。   分块的md5在webuploader组件的cutefile 中

        // file为分块对应的file对象。
        //放入upyun 分块参数  参数组
        console.log(block);
        block.md5=blockshash.shift();
        var options={
            save_token:saveToken.save_token,
            expiration: config.expiration,
            block_index:block.chunk,
            block_hash:block.md5,
        }
        //分块时formapi 就是前一次请求返回的token_secret

        var signature = calcSign(options, saveToken.token_secret);
        var policy = Base64.encode(JSON.stringify(options));
        console.log("block option",options,"token_secret",saveToken.token_secret);

        data.policy=policy;
        data.signature=signature;

        
        // 删除其他数据
         delete data.id;
         delete data.name;
         delete data.type;
         delete data.lastModifiedDate;
         delete data.size;
         delete data.chunks;

    });
    //完成一个分块时重置token_secret
    uploader.on("uploadAccept",function(obj,ret){
        console.log(obj);
        console.log(ret);
        saveToken.token_secret=ret.token_secret;
        console.log(saveToken.token_secret);
    });
    //完成分块上传时发出合并请求
    uploader.on("uploadSuccess",function(obj,ret){
        console.log(ret,obj);
        var options = {
            'save_token': saveToken.save_token,
            'expiration': config.expiration
        };

        var signature = calcSign(options, saveToken.token_secret);
        var policy = Base64.encode(JSON.stringify(options));
        var formParams = {
            policy: policy,
            signature: signature
        };
        var formParamsUrlenc = formatParams(formParams);

        // var options={
        //     save_token:saveToken.save_token,
        //     expiration:config.expiration
        // }
        console.log("完成 开始合并",options,saveToken.save_token)
        // var signature = calcSign(options, saveToken.token_secret);
        // var policy = Base64.encode(JSON.stringify(options));

        // var paramsData = {
        //     policy: policy,
        //     signature: signature
        // };
        // var urlencParams = formatParams(paramsData);
        var request = new XMLHttpRequest();
        request.open('POST', config.api + config.bucket + '/');
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.onload = function(e) {
            if (request.status == 200) {
                var obj=JSON.parse(request.response);
                console.log("path",obj.path);

            }
        };
        request.send(formParamsUrlenc);
    });
    // 当有文件添加进来时执行，负责view的创建
    function addFile( file ) {
        var $li = $( '<li id="' + file.id + '">' +
                '<p class="title">' + file.name + '</p>' +
                '<p class="imgWrap"></p>'+
                '<p class="progress"><span></span></p>' +
                '</li>' ),

            $btns = $('<div>' +
                //'<span class="cancel">删除</span>' +
                //'<span class="rotateRight">向右旋转</span>' +
                //'<span class="rotateLeft">向左旋转</span>'+
                '</div>').appendTo( $li ),
            $prgress = $li.find('p.progress span'),
            $wrap = $li.find( 'p.imgWrap' ),
            $info = $('<p class="error"></p>'),

            showError = function( code ) {
                switch( code ) {
                    case 'exceed_size':
                        text = '文件大小超出';
                        break;

                    case 'interrupt':
                        text = '上传暂停';
                        break;

                    default:
                        text = '上传失败，请重试';
                        break;
                }

                $info.text( text ).appendTo( $li );
            };

        if ( file.getStatus() === 'invalid' ) {
            showError( file.statusText );
        } else {
            // @todo lazyload
            // $wrap.text( '预览中' );
            // uploader.makeThumb( file, function( error, src ) {
            //     if ( error ) {
            //         $wrap.text( '不能预览' );
            //         return;
            //     }

            //     var img = $('<img src="'+src+'">');
            //     $wrap.empty().append( img );
            // }, thumbnailWidth, thumbnailHeight );

            percentages[ file.id ] = [ file.size, 0 ];
            file.rotation = 0;
        }

        file.on('statuschange', function( cur, prev ) {
            if ( prev === 'progress' ) {
                $prgress.hide().width(0);
            } else if ( prev === 'queued' ) {
                $li.off( 'mouseenter mouseleave' );
                $btns.remove();
            }

            // 成功
            if ( cur === 'error' || cur === 'invalid' ) {
                
                console.log( file.statusText );
                showError( file.statusText );
                percentages[ file.id ][ 1 ] = 1;
            } else if ( cur === 'interrupt' ) {
                showError( 'interrupt' );
            } else if ( cur === 'queued' ) {
                percentages[ file.id ][ 1 ] = 0;
            } else if ( cur === 'progress' ) {
                $info.remove();
                $prgress.css('display', 'block');
            } else if ( cur === 'complete' ) {
                $li.append( '<span class="success"></span>' );
            }

            $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
        });

        $li.on( 'mouseenter', function() {
            $btns.stop().animate({height: 30});
        });

        $li.on( 'mouseleave', function() {
            $btns.stop().animate({height: 0});
        });

        $btns.on( 'click', 'span', function() {
            var index = $(this).index(),
                deg;

            switch ( index ) {
                case 0:
                    uploader.removeFile( file );
                    return;

                case 1:
                    file.rotation += 90;
                    break;

                case 2:
                    file.rotation -= 90;
                    break;
            }

            if ( supportTransition ) {
                deg = 'rotate(' + file.rotation + 'deg)';
                $wrap.css({
                    '-webkit-transform': deg,
                    '-mos-transform': deg,
                    '-o-transform': deg,
                    'transform': deg
                });
            } else {
                $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
                // use jquery animate to rotation
                // $({
                //     rotation: rotation
                // }).animate({
                //     rotation: file.rotation
                // }, {
                //     easing: 'linear',
                //     step: function( now ) {
                //         now = now * Math.PI / 180;

                //         var cos = Math.cos( now ),
                //             sin = Math.sin( now );

                //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
                //     }
                // });
            }


        });

        $li.appendTo( $queue );
    }

    // 负责view的销毁
    function removeFile( file ) {
        var $li = $('#'+file.id);

        delete percentages[ file.id ];
        updateTotalProgress();
        $li.off().find('.file-panel').off().end().remove();
    }

    function updateTotalProgress() {
        var loaded = 0,
            total = 0,
            spans = $progress.children(),
            percent;

        $.each( percentages, function( k, v ) {
            total += v[ 0 ];
            loaded += v[ 0 ] * v[ 1 ];
        } );

        percent = total ? loaded / total : 0;

        spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
        spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
        updateStatus();
    }

    function updateStatus() {
        var text = '', stats;

        if ( state === 'ready' ) {
            // text = '选中' + fileCount + '张图片，共' +
            //         WebUploader.formatSize( fileSize ) + '。';
            text='共'+WebUploader.formatSize( fileSize );
        } else if ( state === 'confirm' ) {
            stats = uploader.getStats();
            // if ( stats.uploadFailNum ) {
            //     text = '已成功上传'+
            //         stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
            // }

        } else {
            stats = uploader.getStats();
            text = '共' + fileCount + '个（' +
                    WebUploader.formatSize( fileSize )  +
                    '），已上传' + stats.successNum + '个';

            if ( stats.uploadFailNum ) {
                text += '，失败' + stats.uploadFailNum + '个';
            }

        }

        $info.html( text );
    }

    function setState( val ) {
        var file, stats;

        if ( val === state ) {
            return;
        }

        $upload.removeClass( 'state-' + state );
        $upload.addClass( 'state-' + val );
        state = val;

        switch ( state ) {
            case 'pedding':
                //$placeHolder.removeClass( 'element-invisible' );
                $queue.parent().removeClass('filled');
                $queue.hide();
                //$statusBar.addClass( 'element-invisible' );
                uploader.refresh();
                break;

            case 'ready':
                $placeHolder.addClass( 'element-invisible' );
                $( '#filePicker2' ).removeClass( 'element-invisible');
                $queue.parent().addClass('filled');
                $queue.show();
                //$statusBar.removeClass('element-invisible');
                uploader.refresh();
                break;

            case 'uploading':
                $( '#filePicker2' ).addClass( 'element-invisible' );
                $progress.show();
                $upload.text( '暂停上传' );
                break;

            case 'paused':
                $progress.show();
                $upload.text( '继续上传' );
                break;

            case 'confirm':
                $progress.hide();
                //$upload.text( '开始上传' ).addClass( 'disabled' );

                stats = uploader.getStats();
                if ( stats.successNum && !stats.uploadFailNum ) {
                    setState( 'finish' );
                    return;
                }
                break;
            case 'finish':
                stats = uploader.getStats();
                if ( stats.successNum ) {
                    //alert( '上传成功' );
                } else {
                    // 没有成功的图片，重设
                    state = 'done';
                    location.reload();

                }
                break;
        }

        updateStatus();
    }

    //文件开始上传
    uploader.onUploadStart=function(file){
        
        console.log("文件开始上传");
    }
    uploader.onUploadProgress = function( file, percentage ) {
        var $li = $('#'+file.id),
            $percent = $li.find('.progress span');

        $percent.css( 'width', percentage * 100 + '%' );
        percentages[ file.id ][ 1 ] = percentage;
        updateTotalProgress();
    };

    uploader.onBeforeFileQueued=function(){
        $placeHolder.addClass( 'element-invisible' );
            $statusBar.show();
    }
    //文件加入队列
    uploader.onFileQueued = function( file ) {    
        fileCount++;
        fileSize += file.size;

        if ( fileCount === 1 ) {
            $placeHolder.addClass( 'element-invisible' );
            $statusBar.show();
        }

        addFile( file );
        setState( 'ready' );
        updateTotalProgress();
        //console.log(file);
        //好像uploader.md5计算出的md5有问题   webuploder使用的不是原生的File
        var fileReader = new FileReader();
        //var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
        var blobPacket = blobSlice.call(file.getSource().source, 0, file.size);
        fileReader.onload=function(e){
            file.hash=SparkMD5.ArrayBuffer.hash(e.target.result);
          //  console.log(file);
            chunkInfo.file_hash=file.hash;
            chunkInfo.file_size=file.size;
            console.log("chunkInfo",chunkInfo);
            getToken(file);
        }
        fileReader.readAsArrayBuffer(blobPacket);
    };
    uploader.onUploadFinished=function(){
        $(".uploadBtn").remove();
    }
    uploader.onFileDequeued = function( file ) {
        fileCount--;
        fileSize -= file.size;

        if ( !fileCount ) {
            setState( 'pedding' );
        }

        removeFile( file );
        updateTotalProgress();
        
    };

    uploader.on( 'all', function( type , arg1, arg2 ) {
        var stats;
        //console.log(arg1,arg2)
        console.log(type);
        switch( type ) {
            case 'uploadFinished':
                setState( 'confirm' );
                break;

            case 'startUpload':
                setState( 'uploading' );
                break;

            case 'stopUpload':
                setState( 'paused' );
                break;

        }
    });

    uploader.onError = function( code ) {
        alert( 'Eroor: ' + code );
    };

    $upload.on('click', function() {
        if ( $(this).hasClass( 'disabled' ) ) {
            return false;
        }

        if ( state === 'ready' ) {
            uploader.upload();
        } else if ( state === 'paused' ) {
            uploader.upload();
        } else if ( state === 'uploading' ) {
            uploader.stop();
        }
    });

    $info.on( 'click', '.retry', function() {
        uploader.retry();
    } );

    $info.on( 'click', '.ignore', function() {
        alert( 'todo' );
    } );

    $upload.addClass( 'state-' + state );
    updateTotalProgress();
});